/**
 * 配置封装axios
*/

import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import router from '../router';

axios.defaults.baseURL = 'http://127.0.0.1:3000';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [
  (data) => qs.stringify(data),
];

// 请求拦截器
axios.interceptors.request.use((config) => {
  const conf = config;
  conf.headers.authorization = localStorage.token;
  return conf;
}, (error) => Promise.reject(error));

// 响应连接器
axios.interceptors.response.use((response) => response, (error) => {
  const { status } = error.request;
  switch (status) {
    case 400:
      Message.error('登录失败');
      break;
    case 401:
      localStorage.removeItem('token');
      router.push({ name: 'login' });
      break;
    case 404:
      Message.error('接口不存在');
      break;
    default:
      break;
  }
  return Promise.reject(error);
});

export default axios;
